package cn.yudao.pet.service.impl;

import cn.yudao.basic.exception.BusinessException;
import cn.yudao.basic.utils.BaiduAuditUtils;
import cn.yudao.basic.utils.CodeGenerateUtils;
import cn.yudao.basic.utils.DistanceUtil;
import cn.yudao.basic.utils.Point;
import cn.yudao.order.domain.OrderPetAcquisition;
import cn.yudao.order.domain.OrderPetAcquisitionLog;
import cn.yudao.order.mapper.OrderPetAcquisitionLogMapper;
import cn.yudao.order.mapper.OrderPetAcquisitionMapper;
import cn.yudao.order.service.IOrderPetAcquisitionService;
import cn.yudao.org.domain.Employee;
import cn.yudao.org.domain.Shop;
import cn.yudao.org.mapper.EmployeeMapper;
import cn.yudao.org.mapper.ShopMapper;
import cn.yudao.pet.domain.Pet;
import cn.yudao.pet.domain.SearchMasterMsg;
import cn.yudao.pet.domain.SearchMasterMsgAuditLog;
import cn.yudao.pet.dto.AcceptDto;
import cn.yudao.pet.mapper.PetMapper;
import cn.yudao.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.yudao.pet.mapper.SearchMasterMsgMapper;
import cn.yudao.pet.service.ISearchMasterMsgService;
import cn.yudao.basic.service.impl.BaseServiceImpl;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yudao
 * @since 2022-07-19
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {


    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;

    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private PetMapper petMapper;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    @Autowired
    private OrderPetAcquisitionLogMapper orderPetAcquisitionLogMapper;

    @Value("${rocketmq.producer.send-message-timeout}")
    private Integer messageTimeOut;

    /**
     * @Title: publish
     * @Description: 寻主信息发布
     * @Author: Mr.Jia
     * @Version: 1.0
     * @Date: 2022/7/19 16:16
     * @Parameters:
     * @Return
     */
    @Override
    @Transactional
    public void publish(SearchMasterMsg searchMasterMsg) {
        // 审核关键字段是否存在
        String title = searchMasterMsg.getTitle(); // 标题
        String address = searchMasterMsg.getAddress(); // 地址
        BigDecimal price = searchMasterMsg.getPrice(); // 价格
        if (StringUtils.isEmpty(title) || StringUtils.isEmpty(address) || StringUtils.isEmpty(price))
            throw new BusinessException("请填写你的关键信息");
        // 保存当前信息
        searchMasterMsgMapper.save(searchMasterMsg);
        // 使用百度ai智能审核信息是否合规
        StringBuffer str = new StringBuffer();
        str.append(title)
                .append(address + ",")
                .append(searchMasterMsg.getCoatColor() + ",")
                .append(searchMasterMsg.getName() + ",");
        // 判断如果没有通过百度ai智能审核
        if (!BaiduAuditUtils.TextCensor(str.toString())) {
            // 使用自定义方法添加日志表
            checkResultsSendLog(searchMasterMsg, 0, str);
        } else {
            // 使用自定义方法添加日志表
            checkResultsSendLog(searchMasterMsg, 1, str);
            // 获取所有店铺
            List<Shop> shops = shopMapper.LoadAll();
            // 获取电器用户填写地址的经纬度
            Point point = DistanceUtil.getPoint(searchMasterMsg.getAddress());
            // 使用工具类查询与当前用户地址50km之内最近的shop
            Shop nearestShop = DistanceUtil.getNearestShop(point, shops);
            // 判断店铺是否存在
            if (nearestShop != null) {
                searchMasterMsg.setShopId(nearestShop.getId());
            }
        }
        searchMasterMsgMapper.upadte(searchMasterMsg);
    }

    /**
    * @Title: acceptOrder
    * @Description: 提交订单业务
    * @Author: Mr.Jia
    * @Version: 1.0
    * @Date:  2022/7/20 14:48
    * @Parameters:
    * @Return
    */
    @Override
    @Transactional
    public void acceptOrder(AcceptDto acceptDto) {
        // 非空判断
        Long msgId = acceptDto.getMsgId(); // 寻主信息id
        Long handler = acceptDto.getHandler(); // 接单员工id
        String note = acceptDto.getNote(); // 备注信息
        if (msgId == null || handler == null || StringUtils.isEmpty(note))
            throw new BusinessException("信息为空，请重试");
        // 先查询数据库中是否存在当前的订单表根据寻主信息的id查询
        OrderPetAcquisition orderPetAcquisition1 = orderPetAcquisitionMapper.loadByMsgId(msgId);
        // 如果订单不存在或者订单状态为-1则表示可以接单
        if (orderPetAcquisition1 != null && orderPetAcquisition1.getState() != -1){
            throw new BusinessException("订单已被领取");
        }
        // 生成宠物信息并添加
        // 1.先获取当前宠物的寻主信息
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.loadById(msgId);
        // 2.创建一个宠物对象
        Pet pet = new Pet();
        // 3.给宠物对象的字段赋值
        pet.setName(searchMasterMsg.getName());
        pet.setCostprice(searchMasterMsg.getPrice());
        Employee employee = employeeMapper.loadById(handler);
        pet.setShopId(employee.getShopId());
        pet.setSearchMasterMsgId(msgId);
        petMapper.save(pet);
        // 添加订单信息
        String orderSn = CodeGenerateUtils.generateOrderSn(searchMasterMsg.getUserId());
        OrderPetAcquisition orderPetAcquisition = new OrderPetAcquisition();
        orderPetAcquisition.setOrderSn(orderSn); // 编号
        orderPetAcquisition.setDigest(searchMasterMsg.getName() + "的收购订单"); // 名称
        //    private Date lastcomfirmtime;
        orderPetAcquisition.setLastcomfirmtime(new Date(System.currentTimeMillis() + 2 * 24 * 60 * 60 * 1000)); // 设置时间
        //    private Long petId;
        orderPetAcquisition.setPetId(pet.getId());
        orderPetAcquisition.setPrice(searchMasterMsg.getPrice());
        //    private Long userId;
        orderPetAcquisition.setUserId(searchMasterMsg.getUserId());
        //    private Long shopId;
        orderPetAcquisition.setShopId(searchMasterMsg.getShopId());
        //    private String address;\
        orderPetAcquisition.setAddress(searchMasterMsg.getAddress());
        orderPetAcquisition.setEmpId(handler);
        //    private Long searchMasterMsgId;
        orderPetAcquisition.setSearchMasterMsgId(msgId);
        orderPetAcquisitionMapper.save(orderPetAcquisition);
        // 调用消息发送方法传入订单id
        productMq(orderPetAcquisition.getId());
    }

    /**
    * @Title: sendMq
    * @Description: mq生产者
    * @Author: Mr.Jia
    * @Version: 1.0
    * @Date:  2022/7/25 20:34
    * @Parameters:
    * @Return
    */
    public void productMq(Long id){
        // 将订单id转换为string类型
        String s = id.toString();
        // 发送延迟同步消息，延迟等级为7
        // messageTimeOut 发送消息超时时间
        // MessageBuilder.withPayload(s).build()发送的消息
        // order 发送的topic
        SendResult order = rocketMQTemplate.syncSend("order", MessageBuilder.withPayload(s).build(), messageTimeOut, 7);
        // 打印发送结果
        System.out.println(order);
    }

    /**
    * @Title: cancel
    * @Description: 超时处理
    * @Author: Mr.Jia
    * @Version: 1.0
    * @Date:  2022/7/25 20:57
    * @Parameters:
    * @Return
    */
    public void cancel(Long id) {
        // 根据id查询到当前订单表对应的数据
        OrderPetAcquisition orderPetAcquisition = orderPetAcquisitionMapper.loadById(id);
        // 设置订单状态为null
        orderPetAcquisition.setState(-1);
        orderPetAcquisition.setPetId(null);
        orderPetAcquisition.setUserId(null);
        orderPetAcquisitionMapper.upadte(orderPetAcquisition);
        // 我们先根据订单中的msgid查询到对应的寻主信息msg
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.loadById(orderPetAcquisition.getSearchMasterMsgId());
        // 删除寻主信息的shopid -- 放入寻主池中
        searchMasterMsg.setShopId(null);
        searchMasterMsgMapper.upadte(searchMasterMsg);
        // 删除当前店铺的pet中相关的宠物信息
        petMapper.removeById(orderPetAcquisition.getPetId());
        // 新增一个订单失败的日志表
        extracted(0,orderPetAcquisition);
    }


    /**
     * @Title: extracted
     * @Description: 超时日志表
     * @Author: Mr.Jia
     * @Version: 1.0
     * @Date:  2022/7/20 20:20
     * @Parameters:
     * @Return
     */
    private void extracted(Integer state,OrderPetAcquisition orderPetAcquisition) {
        Long id = orderPetAcquisition.getId();
        OrderPetAcquisitionLog orderPetAcquisitionLog = new OrderPetAcquisitionLog();
        orderPetAcquisitionLog.setAcqId(id);
        orderPetAcquisitionLog.setAuditTime(new Date());
        orderPetAcquisitionLog.setState(state);
        orderPetAcquisitionLog.setNote("订单超时");
        orderPetAcquisitionLogMapper.save(orderPetAcquisitionLog);
    }



    /**
    * @Title: reject
    * @Description: 拒绝订单业务层
    * @Author: Mr.Jia
    * @Version: 1.0
    * @Date:  2022/7/20 17:01
    * @Parameters:
    * @Return
    */
    @Override
    public void reject(Long id) {
        // 修改寻主信息的shopid为null 放回寻主池
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.loadById(id);
        searchMasterMsg.setShopId(null);
        searchMasterMsgMapper.upadte(searchMasterMsg);
        // 生成日志
        SearchMasterMsgAuditLog searchMasterMsgAuditLog = new SearchMasterMsgAuditLog();
        // 给日志信息赋值

    }


    /**
     * @Title: checkResultsSendLog
     * @Description: 根据百度ai的审核结果进行对日志表的赋值和增加
     * @Author: Mr.Jia
     * @Version: 1.0
     * @Date: 2022/7/19 18:34
     * @Parameters:
     * @Return
     */
    @Transactional
    public void checkResultsSendLog(SearchMasterMsg searchMasterMsg, Integer type, StringBuffer str) {
        // 设置当前宠物寻主信息状态为审核通过
        searchMasterMsg.setState(type); // 0 待审核 1 审核通过 -1 驳回
        // 添加日志信息
        SearchMasterMsgAuditLog searchMasterMsgAuditLog = new SearchMasterMsgAuditLog();
        // 给日志信息赋值
        searchMasterMsgAuditLog.setMsgId(searchMasterMsg.getId());
        searchMasterMsgAuditLog.setAuditTime(new Date());
        if (type == 1) {
            searchMasterMsgAuditLog.setNote("审核通过");
            searchMasterMsgAuditLog.setState(1);
        } else if (type == 0){
            searchMasterMsgAuditLog.setNote("违规,违规信息为--" + str.toString());
            searchMasterMsgAuditLog.setState(0);
        }
        searchMasterMsgAuditLogMapper.save(searchMasterMsgAuditLog);
    }
}
